import Mock from "mockjs";

// =================== 初始化学生数据 ===================
let students = JSON.parse(sessionStorage.getItem("students")) || [];

if (!students.length) {
    students = Mock.mock({
        'students|100': [
            {
                id: '@increment',
                name: '@cname',
                gender: '@pick(["男", "女"])',
                'age|18-25': 1,
                major: '@ctitle(3, 5)',
                class: '@string("number", 2)-@string("number", 1)'
            },
        ],
    }).students;

    saveToSessionStorage();
}

// 保存数据到 SessionStorage 的函数
function saveToSessionStorage() {
    sessionStorage.setItem("students", JSON.stringify(students));
}

// 获取下一个唯一学号
function getNextId() {
    return students.length > 0 ? Math.max(...students.map((s) => s.id)) + 1 : 1;
}

// =================== 登录接口 ===================
Mock.mock("/api/login", "post", (options) => {
    const body = JSON.parse(options.body);
    if (body.username === "admin" && body.password === "123456") {
        return { code: 200, message: "登录成功", token: "mock-token" };
    }
    return { code: 401, message: "用户名或密码错误" };
});

// =================== 获取学生列表接口 ===================
Mock.mock(/\/api\/students/, "get", (req) => {
    const urlParams = new URLSearchParams(req.url.split("?")[1]);
    const page = parseInt(urlParams.get("page")) || 1;
    const pageSize = parseInt(urlParams.get("pageSize")) || 10;
    const searchQuery = urlParams.get("searchQuery") || "";
    const sortField = urlParams.get("sortField") || "";
    const sortOrder = urlParams.get("sortOrder") || "asc";

    let filtered = students;

    // 支持学号和姓名搜索
    if (searchQuery) {
        filtered = filtered.filter((student) => {
            const idString = String(student.id); // 学号转为字符串
            return student.name.includes(searchQuery) || idString.includes(searchQuery);
        });
    }

    console.log("搜索关键词：", searchQuery);
    console.log("过滤后的数据：", filtered);

    // 排序
    if (sortField) {
        filtered.sort((a, b) => {
            if (sortOrder === "asc") {
                return a[sortField] > b[sortField] ? 1 : -1;
            } else {
                return a[sortField] < b[sortField] ? 1 : -1;
            }
        });
    }

    // 分页
    const start = (page - 1) * pageSize;
    const end = page * pageSize;
    const paginatedStudents = filtered.slice(start, end);

    return {
        code: 200,
        data: {
            total: filtered.length,
            students: paginatedStudents,
        },
        message: "获取成功",
    };
});

// =================== 新增学生接口 ===================
Mock.mock("/api/students", "post", (req) => {
    const newStudent = JSON.parse(req.body);

    // 自动生成唯一学号
    newStudent.id = getNextId();

    students.push(newStudent);
    saveToSessionStorage(); // 同步到 SessionStorage

    return { code: 200, message: "新增成功", student: newStudent };
});

// =================== 编辑学生接口 ===================
Mock.mock(/\/api\/students\/\d+/, "put", (req) => {
    const updatedStudent = JSON.parse(req.body);
    const studentId = parseInt(req.url.split("/").pop());

    // 查找学生
    const oldIndex = students.findIndex((s) => s.id === studentId);
    if (oldIndex === -1) {
        return { code: 404, message: "学生不存在" };
    }

    // 更新除学号以外的字段
    students[oldIndex] = {
        ...students[oldIndex],
        ...updatedStudent,
        id: students[oldIndex].id, // 确保学号不变
    };

    saveToSessionStorage(); // 同步到 SessionStorage

    return { code: 200, message: "编辑成功" };
});

// =================== 删除学生接口 ===================
Mock.mock(/\/api\/students\/\d+/, "delete", (req) => {
    const studentId = parseInt(req.url.split("/").pop());

    // 过滤掉指定 ID 的学生
    const newStudents = students.filter((s) => s.id !== studentId);

    if (newStudents.length === students.length) {
        return { code: 404, message: "学生不存在" };
    }

    students = newStudents;
    saveToSessionStorage(); // 同步到 SessionStorage

    return { code: 200, message: "删除成功" };
});
